<?php

namespace addons\facrm\controller\facrm\analysis;

use addons\facrm\library\BackendApi;
use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;


/**
 * 员工分析
 */
class Admin extends BackendApi
{
    protected $model = null;
    protected $searchFields = 'id,username,nickname';
    protected $groupList = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('app\admin\model\Admin');

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $this->groupList = $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init($groupList);
        $this->request->filter(['strip_tags']);

    }

    /**
     * 工作数据分析
     * @return array|bool|string|\think\response\Json
     * @throws \think\Exception
     */
    public function index()
    {
        // 本月第一天
        $first_day = date('Y-m-01 0:0:0', time());
        // 本月最后一天
        $last_day = date('Y-m-d 23:59:59', strtotime("$first_day +1 month -1 day"));


        $startDate = $this->request->param('start_date', $first_day);
        $endDate = $this->request->param('end_date', $last_day);
        $owner_user_id = $this->request->param('owner_user_id', 0, 'intval');
        $group_id = $this->request->param('group_id', 0, 'intval');
        $owner_user_ids = array();
        if ($owner_user_id > 0) {
            $owner_user_ids[] = $owner_user_id;
        } elseif ($group_id && $group_id > 0) {
            Tree::instance()->init($this->groupList);
            $groupIds = Tree::instance()->getChildrenIds($group_id, true);

            $authGroupList = \app\admin\model\AuthGroupAccess::
            field('uid,group_id')
                ->where('group_id', 'in', $groupIds)
                ->select();

            foreach ($authGroupList as $k => $v) {
                if ($owner_user_ids && in_array($v['uid'], $owner_user_ids)) continue;
                $owner_user_ids[] = $v['uid'];
            }
            if (!$owner_user_ids) {
                $this->error(__("没有数据"));
            }
        } else {
            $owner_user_ids[] = $this->auth->id;
        }


        $customer_data = $this->getCustomerEchartData($startDate,$endDate,$owner_user_ids);
        //跟进次数
        $record_data = $this->getRecordEchartData($startDate,$endDate,$owner_user_ids);
        $business_data = $this->getBusinessEchartData($startDate,$endDate,$owner_user_ids);

        $totaldata['m_add_count'] = array_sum($customer_data['data'][__("客户增量")]);
        $totaldata['r_m_count'] = array_sum($record_data['data'][__("跟进客户")]);
        $totaldata['r_add_count'] = array_sum($record_data['data'][__("跟进次数")]);
        $totaldata['b_add_count'] = array_sum($business_data['data'][__("新增商机")]);

        $result = array("customer_data" => $customer_data, "record_data" => $record_data, 'business_data' => $business_data, 'totaldata' => $totaldata);
        $this->success('', $result);
    }

    /**
     * 跟进分析
     * @return \think\response\Json|void
     */
    public function record()
    {

        if ($this->request->param('ajax') == 1) {
            return $this->getRecordEchartData();
        } elseif ($this->request->param('ajax') == 2) {
            return $this->getRecordTypeEchartData();
        }

        $recordModel = new \app\admin\model\facrm\Record();
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model
            ->where($where)
            ->order($sort, $order)
            ->count();

        $list = $this->model
            ->where($where)
            ->field(['password', 'salt', 'token'], true)
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();
        foreach ($list as &$row) {
            //跟进总次数
            $row['record_count'] = $recordModel->where('create_user_id', $row->id)->where('types', "customer")->count();
            $row['customer_count'] = $recordModel->where('create_user_id', $row->id)->where('types', "customer")->group('types_id')->count();//跟进客户数
        }
        $result = array("total" => $total, "rows" => $list);
        $this->success('', $result);

    }


    /**
     * 业绩分析
     */
    public function achievement()
    {
        return $this->getAchievementEchart();
    }

    /**
     * 获取最近增量和成交量
     * @return bool
     */
    private function getCustomerEchartData($startDate,$endDate,$owner_user_ids)
    {
        $owner_user_id = $owner_user_ids;
        $customerModel = new \app\admin\model\facrm\Customer();
        // 生成查询的开始和结束时间，默认取30日
        !is_numeric($startDate) && $starttime = strtotime($startDate);
        !is_numeric($endDate) && $endtime = strtotime($endDate);
        $isnotrangeDate = empty($starttime) && empty($endtime);

        $nearly = '30';
        if ($isnotrangeDate) {
            $endtime = time();
            $nearly -= 1;
            $starttime = strtotime("-{$nearly} day");  // 最近30天日期
        } elseif ($starttime > $endtime) {
            $this->error = __('起始时间要小于终止时间');
            return false;
        }
        $totalseconds = $endtime - $starttime;;
        if ($totalseconds > 86400 * 30 * 2) {
            $format = '%Y-%m';
        } else {
            if ($totalseconds > 86400) {
                $format = '%Y-%m-%d';
            } else {
                $format = '%H:00';
            }
        }
        //客户增量
        if ($owner_user_id) {
            $customerModel->where('owner_user_id', 'in', $owner_user_id);
        }
        $lists = $customerModel->where('collect_time', 'between time', [$starttime, $endtime])
            ->field('COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(collect_time), "' . $format . '") AS add_date')
            ->group('add_date')
            ->select();

        if ($totalseconds > 84600 * 30 * 2) {
            $starttime = strtotime('last month', $starttime);
            while (($starttime = strtotime('next month', $starttime)) <= $endtime) {
                $column[] = date('Y-m', $starttime);
            }
        } else {
            if ($totalseconds > 86400) {
                for ($time = $starttime; $time <= $endtime;) {
                    $column[] = date("Y-m-d", $time);
                    $time += 86400;
                }
            } else {
                for ($time = $starttime; $time <= $endtime;) {
                    $column[] = date("H:00", $time);
                    $time += 3600;
                }
            }
        }


        $c_count = $d_count = array_fill_keys($column, 0);

        foreach ($lists as $k => $v) {
            $c_count[$v['add_date']] = $v['nums'];//客户增量
        }



        $result = [
            'date' => array_keys($c_count),
            'c_count' => array_values($c_count),
        ];

        $data = [
            'date' => $result['date'],
            'data' => [

                __("客户增量") => $result['c_count'],

            ],
        ];
        return $data;

    }


    /**
     * 跟进趋势
     * @return bool
     */
    private function getRecordEchartData($startDate,$endDate,$owner_user_ids)
    {
        $recordModel = new \app\admin\model\facrm\Record();
        $data = $recordModel->getRecordEchartData($startDate, $endDate, $owner_user_ids);
        return $data;
    }

    /**
     * 商机趋势
     * @return bool
     */
    private function getBusinessEchartData($startDate,$endDate,$owner_user_ids)
    {

        $recordModel = new \app\admin\model\facrm\Business();
        $data = $recordModel->getEchartData($startDate, $endDate, $owner_user_ids);

        return $data;

    }

    /**
     * 跟进分析
     * @param bool $is_ajax
     * @return mixed
     * @throws \think\Exception
     */
    private function getRecordTypeEchartData($is_ajax = true)
    {
        $startDate = $this->request->param('start_date', null);
        $endDate = $this->request->param('end_date', null);
        $owner_user_id = $this->request->param('owner_user_id', 0, 'intval');
        // 生成查询的开始和结束时间，默认取30日
        !is_numeric($startDate) && $starttime = strtotime($startDate);
        !is_numeric($endDate) && $endtime = strtotime($endDate);

        $config = get_addon_config('facrm');
        $recordModel = new \app\admin\model\facrm\Record();
        foreach ($config['record_type'] as $k => $v) {
            if ($starttime) {
                $recordModel->where('create_time', 'between time', [$starttime, $endtime]);
            }
            if ($owner_user_id) {
                $recordModel->where('create_user_id', $owner_user_id);
            }
            $r['name'] = $v;
            $r['value'] = $recordModel->where('types', 'customer')->where('record_type', $k)->count();
            $alldata[] = $r;
        }
        if ($is_ajax) {
            $this->success('', '', [
                'record' => $alldata
            ]);
        } else {
            return $alldata;
        }

    }

    /**
     * 业绩分析
     * @param bool $is_ajax
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getAchievementEchart($is_ajax = true)
    {
        // 本月第一天
        $first_day = date('Y-m-01 0:0:0', time());
        // 本月最后一天
        $last_day = date('Y-m-d 23:59:59', strtotime("$first_day +1 month -1 day"));


        $startDate = $this->request->param('start_date', $first_day);
        $endDate = $this->request->param('end_date', $last_day);
        $owner_user_id = $this->request->param('owner_user_id', 0, 'intval');
        $group_id = $this->request->param('group_id', 0, 'intval');
        $owner_user_ids = array();
        if ($owner_user_id > 0) {
            $owner_user_ids[] = $owner_user_id;
        } elseif ($group_id && $group_id > 0) {
            Tree::instance()->init($this->groupList);
            $groupIds = Tree::instance()->getChildrenIds($group_id, true);

            $authGroupList = \app\admin\model\AuthGroupAccess::
            field('uid,group_id')
                ->where('group_id', 'in', $groupIds)
                ->select();

            foreach ($authGroupList as $k => $v) {
                if ($owner_user_ids && in_array($v['uid'], $owner_user_ids)) continue;
                $owner_user_ids[] = $v['uid'];
            }
            if (!$owner_user_ids) {
                $this->error(__("没有数据"));
            }
        } else {
            $owner_user_ids[] = $this->auth->id;
        }
        $contractModel = new \app\admin\model\facrm\Contract();
        $data = $contractModel->getAchievementEchart($startDate, $endDate, $owner_user_ids);
        //汇总
        $totaldata['receivables_money'] = array_sum($data['data'][__("回款金额")]);
        $totaldata['receivables_count'] = array_sum($data['data'][__("回款数量")]);
        $totaldata['contract_moeny'] = array_sum($data['data'][__("合同金额")]);
        $totaldata['contract_count'] = array_sum($data['data'][__("合同数量")]);

        //目标计划
        $achievementModel = new  \app\admin\model\facrm\Achievement();
        $contract_data = $achievementModel->getAchievement(1, $startDate, $endDate, ($group_id&&!$owner_user_id) ? 2 : 3,
            $owner_user_id ? $owner_user_id : $group_id, $owner_user_ids);
        $receivables_data = $achievementModel->getAchievement(2, $startDate, $endDate, ($group_id&&!$owner_user_id) ? 2 : 3,
            $owner_user_id ? $owner_user_id : $group_id, $owner_user_ids);

        if ($is_ajax) {
            $this->success('', [
                'achievement' => $data,
                'totaldata' => $totaldata,
                'contract_data' => $contract_data,
                'receivables_data' => $receivables_data,

            ]);
        } else {
            return $data;
        }
    }

}
